//
//  SampuxQRCodeViewController.m
//  Sampux
//
//  Created by rzm on 16/10/13.
//  Copyright © 2016年 GaoBiao. All rights reserved.
//

#import "SampuxQRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "QRView.h"
#import "QRUtil.h"
#import "SPScanAfterViewController.h"
#import "SampuxAddEquipmentViewController.h"

@interface SampuxQRCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate,QRViewDelegate>
@property (strong, nonatomic) AVCaptureDevice * device;
@property (strong, nonatomic) AVCaptureDeviceInput * input;
@property (strong, nonatomic) AVCaptureMetadataOutput * output;
@property (strong, nonatomic) AVCaptureSession * session;
@property (strong, nonatomic) AVCaptureVideoPreviewLayer * preview;

@property (nonatomic, strong) QRView *qrView;

@property (nonatomic, copy) ScanCompleteBlock scanCompleteBlock;

@property (nonatomic, copy, readwrite) NSString *urlString;

@property (nonatomic, strong) UIButton *rightBtn;

@end

@implementation SampuxQRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createBackBarButtonItem];
    self.view.backgroundColor = THSystemWhiteColor;
    [self createRightBackBarButtonItem];
    if ([self canUseCamera] &&[self validateCamera]) {
        [self defaultConfig];       //初始化配置,主要是二维码的配置
    }else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有摄像头或摄像头不可用" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    }
    [self configUI];
    [self updateLayout];

}
-(BOOL)canUseCamera {
    
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        
        NSLog(@"相机权限受限");
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请在设备的设置-隐私-相机中允许访问相机。" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return NO;
    }
    return YES;
}

-(BOOL)validateCamera {
    
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera] &&
    [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (void)createRightBackBarButtonItem
{
    SampuxCustomNavController *_nav = (SampuxCustomNavController *)self.navigationController;
    UIButton *rightBtn = [UIButton createButton];
    [rightBtn setImage:imageNamed(@"feedBackCode") forState:UIControlStateNormal];
    self.rightBtn = rightBtn;
    rightBtn.frame = CGRectMake(kScreenWidth - 10 - 40, 20, 40, 40);
    [rightBtn addTarget:self action:@selector(addBarBtnClick) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.hitTestEdgeInsets = UIEdgeInsetsMake(-10, -10, -10, -20);
    [_nav.img addSubview:self.rightBtn];
}

- (void)addBarBtnClick
{
    SampuxAddEquipmentViewController *addVC = [[SampuxAddEquipmentViewController alloc]init];
    [self.navigationController pushViewController:addVC animated:YES];
    addVC.account = self.urlString;
}

- (void)defaultConfig {
        [self startRunning];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [super viewWillAppear:YES];
    SampuxCustomNavController *_nav = (SampuxCustomNavController *)self.navigationController;
    _nav.titleStr = @"扫描设备二维码";
    _nav.rightBtn.hidden = YES;
    self.rightBtn.hidden = NO;

    if (![_session isRunning]) {
        [self startRunning];
    }
    
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    SampuxCustomNavController *_nav = (SampuxCustomNavController *)self.navigationController;
    _nav.rightBtn.hidden = YES;
    self.rightBtn.hidden = YES;
    [self stopRunning];
}

- (void)configUI {
    
    [self.view addSubview:self.qrView];
    
}

- (void)updateLayout {
    
//    _qrView.center = CGPointMake([QRUtil screenBounds].size.width / 2, [QRUtil screenBounds].size.height / 2);
//    _qrView.backgroundColor = RandomColor;
    //修正扫描区域
    CGFloat screenHeight = self.view.frame.size.height;
    CGFloat screenWidth = self.view.frame.size.width;
//    CGRect cropRect = CGRectMake((screenWidth - self.qrView.transparentArea.width) / 2,
//                                 (screenHeight - self.qrView.transparentArea.height) / 2,
//                                 self.qrView.transparentArea.width,
//                                 self.qrView.transparentArea.height);
   
    CGRect cropRect = CGRectMake((screenWidth - self.qrView.transparentArea.width) / 2,
                                  Sampux6HScale(150),
                                 self.qrView.transparentArea.width,
                                 self.qrView.transparentArea.height);
    
    [_output setRectOfInterest:CGRectMake(cropRect.origin.y / screenHeight,
                                          cropRect.origin.x / screenWidth,
                                          cropRect.size.height / screenHeight,
                                          cropRect.size.width / screenWidth)];
}

- (void)pop:(UIButton *)button {
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Public Method
-(instancetype)initWithScanCompleteHandler:(ScanCompleteBlock)scanCompleteBlock {
    
    self = [super init];
    if (self) {
        _scanCompleteBlock = scanCompleteBlock;
    }
    return self;
}

- (void)startRunning {
    
    
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    
    AVCaptureConnection *outputConnection = [_output connectionWithMediaType:AVMediaTypeVideo];
    outputConnection.videoOrientation = [QRUtil videoOrientationFromCurrentDeviceOrientation];
    
    
    // 条码类型 AVMetadataObjectTypeQRCode
//    _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
    
    BOOL availableQRCodeType = NO;
    
    //是否可以识别二维码
    for (id availableType in _output.availableMetadataObjectTypes) {
        if (availableType && [availableType isKindOfClass:AVMetadataObjectTypeQRCode.class]) {
            if ([[availableType lowercaseString] containsString:@"qrcode"]) {
                availableQRCodeType = YES;
                //                AMLog(@"availableType==%@",availableType);
                break;
            }
        }
    }
    
    //识别二维码
    if (availableQRCodeType) {
        [_output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    }
    
    // Preview
    _preview = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    _preview.videoGravity =AVLayerVideoGravityResize;
    _preview.frame =[QRUtil screenBounds];
    [self.view.layer insertSublayer:_preview atIndex:0];
    
    _preview.connection.videoOrientation = [QRUtil videoOrientationFromCurrentDeviceOrientation];
    
    [_session startRunning];
}

- (void)stopRunning {
    
    [_preview removeFromSuperlayer];
    [_session stopRunning];
    
}

#pragma mark QRViewDelegate
-(void)scanTypeConfig:(QRItem *)item {
    
    if (item.type == QRItemTypeQRCode) {
        _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
        
    } else if (item.type == QRItemTypeOther) {
        
        _output.metadataObjectTypes = @[AVMetadataObjectTypeEAN13Code,
                                        AVMetadataObjectTypeEAN8Code,
                                        AVMetadataObjectTypeCode128Code,
                                        AVMetadataObjectTypeQRCode];
    }
}
#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    NSString *stringValue = @"";
    if ([metadataObjects count] > 0)
    {
        //停止扫描
        [_session stopRunning];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
    }
    
    self.urlString = [stringValue substringToIndex:16];
    
    NSLog(@" 扫描后的url是:%@",self.urlString);
    
    if (self.scanCompleteBlock) {
        self.scanCompleteBlock(stringValue);
    }
    
    SPScanAfterViewController *VC = [[SPScanAfterViewController alloc]init];
    VC.numberString = self.urlString;
    [self.navigationController pushViewController:VC animated:YES];
    //    [_session startRunning];
    
}


-(QRView *)qrView {
    
    if (!_qrView) {
        
        CGRect screenRect = [QRUtil screenBounds];
        _qrView = [[QRView alloc] initWithFrame:screenRect];
        _qrView.transparentArea = CGSizeMake(Sampux6HScale(200), Sampux6HScale(200));
        
        _qrView.backgroundColor = [UIColor clearColor];
        _qrView.delegate = self;
    }
    return _qrView;
}

@end
